local extension = Package("rfenghou_liang")
extension.extensionName = "aaa_fenghou"

local U = require "packages/utility/utility"

Fk:loadTranslationTable{
  ["rfenghou_liang"] = "南梁",
  ["liang"] = "梁",
}

local xiaoyan1 = General:new(extension, "rfenghou__xiaoyan", "liang", 4)

local changdao = fk.CreateTriggerSkill{
  name = "rfenghou__changdao",
  events = {fk.EventPhaseStart},
  can_trigger = function(self, event, target, player, data)
    if target == player and player:hasSkill(self) then
      if target.phase == Player.Start then
        local phaselist = {}
        for _, phase in ipairs({Player.Judge, Player.Draw, Player.Play, Player.Discard}) do
          if not player.skipped_phases[phase] then 
            if (phase + 1 > 3 and phase + 1 < 7 and not player.skipped_phases[phase + 1]) or
            (phase - 1 < 6 and phase - 1 > 2 and not player.skipped_phases[phase - 1]) then
            table.insertIfNeed(phaselist, phase)
            end
          end
        end
      return #phaselist >= 2
    elseif target.phase == Player.Finish then
      return (player.skipped_phases[Player.Draw] and table.find(player.room.alive_players, function(p) 
        for _, id in ipairs(player.room:getOtherPlayers(p)) do return p:canMoveCardsInBoardTo(id) end end))
        or (player:isWounded() and not player.skipped_phases[Player.Discard])
      end
    end
  end,
  on_use = function (self, event, target, player, data)
    local room = player.room
    if target.phase == Player.Start then
      local phaselist = {}
      for _, phase in ipairs({Player.Judge, Player.Draw, Player.Play, Player.Discard}) do
        if not player.skipped_phases[phase] then 
          if (phase + 1 > 3 and phase + 1 < 7 and not player.skipped_phases[phase + 1]) or
          (phase - 1 < 6 and phase - 1 > 2 and not player.skipped_phases[phase - 1]) then
          table.insertIfNeed(phaselist, Util.PhaseStrMapper(phase))
          end
        end
      end
    if #phaselist >= 2 then
      local choice = room:askForChoices(player, phaselist, 2, 2, self.name, "#rfenghou__changdao-skip", false)
      for _, phase in ipairs({Player.Judge, Player.Draw, Player.Play, Player.Discard}) do
        if not player.skipped_phases[phase] then 
          if (table.contains(choice, Util.PhaseStrMapper(phase - 1)) and table.find(choice, function(e) return Util.PhaseStrMapper(e) > phase end))
          or (table.contains(choice, Util.PhaseStrMapper(phase + 1)) and table.find(choice, function(e) return Util.PhaseStrMapper(e) < phase end)) then
          table.insertIfNeed(choice, Util.PhaseStrMapper(phase))
          end
        end
      end
      player:drawCards(#choice, self.name)
      if not player.dead then
        for _, e in ipairs(choice) do
        player:skip(Util.PhaseStrMapper(e))
        end
      end
    end
  elseif target.phase == Player.Finish then
    local choices2 = {}
      if player.skipped_phases[Player.Draw] and player.skipped_phases[Player.Draw] and table.find(player.room.alive_players, function(p) 
        for _, id in ipairs(player.room:getOtherPlayers(p)) do return p:canMoveCardsInBoardTo(id) end end) then
        table.insert(choices2, "changdao__moveOnBoard")
      end
      if player:isWounded() and not player.skipped_phases[Player.Discard] then
        table.insert(choices2, "changdao__recover1")
      end
      if #choices2 > 0 then
        local choice2 = room:askForChoices(player, choices2, 1, #choices2, self.name, "#rfenghou__changdao-invoke", false)
        if table.contains(choice2, "changdao__moveOnBoard") and not player.dead then
          local targets = room:askForChooseToMoveCardInBoard(player, "#rfenghou__changdao-move", self.name, false, nil)
          if #targets ~= 0 then
            targets = table.map(targets, function(id) return room:getPlayerById(id) end)
            room:askForMoveCardInBoard(player, targets[1], targets[2], self.name)
          end
        end
        if table.contains(choice2, "changdao__recover1") and not player.dead then
          player.room:recover({
            who = player,
            num = 1,
            recoverBy = player,
            skillName = self.name
          })
        end
      end
    end
  end,
}

xiaoyan1:addSkill(changdao)

local shifo = fk.CreateTriggerSkill{
  name = "rfenghou__shifo$",
  events = {fk.EventPhaseStart},
  can_trigger = function(self, event, target, player, data)
    if target ~= player and player:hasSkill(self) then
      if target.phase == Player.Judge then
        return target.kingdom == "liang" and #target:getCardIds("j") == 0
      end
    end
  end,
  on_cost = function(self, event, target, player, data)
    return player.room:askForSkillInvoke(target, self.name, data, "#rfenghou__shifo-invoke::"..player.id)
  end,
  on_use = function(self, event, target, player, data)
    local cards = {}
    for _, id in ipairs(U.getUniversalCards(player.room, "t")) do
      if #Fk:getCardById(id):getAvailableTargets(player) > 0 and not Fk:getCardById(id).is_damage_card  then
        table.insertIfNeed(cards, id)
      end
    end
    if #cards == 0 then return false end
    local use = U.askForUseRealCard(player.room, player, cards, nil, self.name, nil, {expand_pile = cards, bypass_times = true, extraUse = true}, true, false)
    if use then
    use.card.skillName = self.name
    player.room:useCard(use)
    end  
  end,
}

xiaoyan1:addSkill(shifo)

Fk:loadTranslationTable{
  [xiaoyan1.name] = "萧衍",
  ["#"..xiaoyan1.name] = "布泽沐邦",
  ["designer:"..xiaoyan1.name] = "扬林",
  ["illustrator:"..xiaoyan1.name] = "王于兴师",

  [changdao.name] = "畅道",
  [":"..changdao.name] = "准备阶段，你可摸二至四张牌，跳过回合内等量个连续的阶段（准备阶段和结束阶段除外）；结束阶段，若当前回合你跳过摸牌阶段，可移动场上一张牌；未跳过弃牌阶段，可回复一点体力。",
  [shifo.name] = "施佛",
  [":"..shifo.name] = "主公技，其他梁势力角色的判定阶段开始时，若其判定区无牌，其可令你视为使用一张不可造成伤害的普通锦囊牌。",

  ["#rfenghou__changdao-skip"] = "畅道：请选择要跳过的两个阶段，你将跳过选项及其间的所有阶段，摸等量张牌。",
  ["#rfenghou__changdao-invoke"] = "畅道",
  ["changdao__moveOnBoard"] = "移动场上一张牌",
  ["changdao__recover1"] = "回复1点体力",
  ["#rfenghou__changdao-move"] = "畅道：请选择两名角色，移动其中一名角色场上的一张牌给另一名角色。",
  ["#rfenghou__shifo-invoke"] = "施佛：是否令 %dest 使用一张非伤害类锦囊牌？",
}

local lanqin = General:new(extension, "rfenghou__lanqin", "liang", 4)

---@param player ServerPlayer
---@param data DamageStruct
local jinghua_on_use = function (player, data)
  if not data.damage then return end
  data.damage = data.damage + 1
  if data.damage >= data.to.hp + data.to.shield then
    player.room:recastCard(player:getCardIds("h"), player, "rfenghou__jinghua")
    if data.damage > 4 then
      return true
    end
  end
end

local jinghua = fk.CreateTriggerSkill{
  name = "rfenghou__jinghua",
  frequency = Skill.Compulsory,
  anim_type = "offensive",
  events = {fk.DamageCaused},
  can_trigger = function (self, event, target, player, data)
    return player == target and player:hasSkill(self)
  end,
  on_use = function (self, event, target, player, data)
    jinghua_on_use(player, data)
  end
}

local jinghua_masochism = fk.CreateTriggerSkill{
  name = "#rfenghou__jinghua_masochism",
  frequency = Skill.Compulsory,
  anim_type = "masochism",
  events = {fk.DamageInflicted},
  can_trigger = function (self, event, target, player, data)
    return player == target and player:hasSkill(self)
  end,
  on_use = function (self, event, target, player, data)
    jinghua_on_use(player, data)
  end
}
jinghua:addRelatedSkill(jinghua_masochism)

lanqin:addSkill(jinghua)

Fk:loadTranslationTable{
  [lanqin.name] = "兰钦",
  ["#"..lanqin.name] = "南镇刺殇",
  ["designer:"..lanqin.name] = "祭祀",
  ["illustrator:"..lanqin.name] = "乱世逐鹿",

  [jinghua.name] = "镜华",
  [":"..jinghua.name] = "锁定技，你造成或受到伤害时，均+1；你造成或受到致命伤害时，须重铸所有手牌，若大于4，防止此伤害。",

  [jinghua_masochism.name] = "镜华",
  [":"..jinghua_masochism.name] = "锁定技，你造成或受到伤害时，均+1；你造成或受到致命伤害时，须重铸所有手牌，若大于4，防止此伤害。"
}

local caojingzong = General:new(extension, "rfenghou__caojingzong", "liang", 4)

--[[local shixiao_viewas = fk.CreateViewAsSkill{
  name = "rfenghou__shixiao_viewas",
  min_card_num = 2,
  max_card_num = 3,
  card_filter = function (self, to_select, selected, player)
    return #selected < 3
  end,
  view_as = function (self, cards, player)
    local card_name
    if #cards == 2 then
      card_name = "slash"
    elseif #cards == 3 then
      card_name = "rfenghou_shoot__slash"
    else
      return nil
    end
    local card = Fk:cloneCard(card_name)
    card.skillName = self.name
    card:addSubcards(cards)
    return card
  end
}
Fk:addSkill(shixiao_viewas)

local shixiao = fk.CreateActiveSkill{
  name = "rfenghou__shixiao",
  can_use = function (self, player, card, extra_data)
    if player:usedSkillTimes(self.name, Player.HistoryPhase) < 1 then
      return player:canUse(Fk:cloneCard("analeptic"))
    end
  end,
  card_num = 0,
  target_num = 0,
  on_use = function (self, room, effect)
    local player = room:getPlayerById(effect.from)
    player:drawCards(3, self.name)
    local analeptic = Fk:cloneCard("analeptic")
    analeptic.skillName = self.name
    if player:canUse(analeptic) then
      room:useCard{
        card = analeptic,
        tos = {{player.id}},
        from = player.id
      }
    end
    if player:isAlive() then
      local cycle = player:getHandcardNum() - player:getMaxCards()
      if cycle > 0 then
        for i = 1, cycle do
          if not player:isAlive() or #player:getCardIds("he") < 2
          or not U.getDefaultTargets(player, Fk:cloneCard("rfenghou_shoot__slash"), true) then
            break
          end
          local _, ret = room:askForUseActiveSkill(
            player, shixiao_viewas.name,
            self.name.."-view_as:::"..string.format("(%s/%s)", i, cycle),
            false, { bypass_times = true, extraUse = true }
          )
          if ret and ret.cards and ret.targets then
            local card_name
            if #ret.cards == 2 then
              card_name = "slash"
            elseif #ret.cards == 3 then
              card_name = "rfenghou_shoot__slash"
            end
            local card = Fk:cloneCard(card_name)
            card.skillName = self.name
            card:addSubcards(ret.cards)
            room:useCard{
              card = card,
              tos = table.map(ret.targets, function(pid) return {pid} end),
              from = player.id
            }
          end
        end
      end
    end
  end
}

local shixiao_negative = fk.CreateTriggerSkill{
  name = "#rfenghou__shixiao_negative",
  frequency = Skill.Compulsory,
  anim_type = "negative",
  events = {fk.EventPhaseEnd},
  can_trigger = function (self, event, target, player, data)
    if player == target and player:hasSkill(self) and player.phase == Player.Discard then
      return #player.room.logic:getEventsOfScope(GameEvent.MoveCards, 1, function (e)
        for _, move in ipairs(e.data) do
          if move.proposer == player.id and move.moveReason == fk.ReasonDiscard then
            return true
          end
        end
      end, Player.HistoryPhase) == 0
    end
  end,
  on_cost = Util.TrueFunc,
  on_use = function (self, event, target, player, data)
    player.room:addPlayerMark(player, MarkEnum.MinusMaxCards, 1)
  end
}

shixiao:addRelatedSkill(shixiao_negative)
caojingzong:addSkill(shixiao) 
]]

local shixiao = fk.CreateActiveSkill{
  name = "rfenghou__shixiao",
  anim_type = "offensive",
  can_use = function(self, player)
    return player:usedSkillTimes(self.name, Player.HistoryPhase) == 0
  end,
  min_target_num = 1,
  max_target_num = 999,
  target_filter = function(self, to_select, selected, selected_cards)
    local target = Fk:currentRoom():getPlayerById(to_select)
    return to_select ~= Self.id and Self:canPindian(target)
  end,
  card_num = 0,
  card_filter = Util.FalseFunc,
  on_use = function(self, room, effect)
    local player = room:getPlayerById(effect.from)
    local targets = table.map(effect.tos, Util.Id2PlayerMapper)
    room:setPlayerMark(player, "@@rfenghou__shixiao-turn", 1)
    local pd = U.jointPindian(player, targets, self.name)
    if pd.winner ~= nil then
      local list = {}
      if pd.fromCard.color == Card.Black then
        table.insert(list, pd.fromCard)
      end
      for _, p in ipairs(targets) do
        if pd.results[p.id].toCard.color == Card.Black then
          table.insert(list, pd.results[p.id].toCard)
        end
      end
      if #list > 0 then
      room:moveCardTo(list, Card.PlayerHand, pd.winner, fk.ReasonJustMove, self.name, "", true, pd.winner.id)
      end
    end
    if pd.winner ~= player and not player.dead then
      local n = player:getHandcardNum()
      for _, p in ipairs(room:getOtherPlayers(player, false)) do
        n = math.min(n, p:getHandcardNum())
      end
      if player:getHandcardNum() > n then
        local throw = room:askForDiscard(player, player:getHandcardNum() - n, player:getHandcardNum() - n, false, self.name, false, ".", "#rfenghou__shixiao-delay")
        local w = 0
        for _, id in ipairs(throw) do
          if Fk:getCardById(id).color == Card.Black then
          w = w + 1
          end
        end
        while w > 0 do
          if player.dead then break end
          room:useVirtualCard("analeptic", nil, player, player, self.name, true)
          w = w - 1
        end
      end
    end
  end,
}

local shixiao_delay = fk.CreateTriggerSkill{
  name = "#rfenghou__shixiao_delay",
  anim_type = "offensive",
  events = {fk.CardUsing},
  can_trigger = function(self, event, target, player, data)
    return player:getMark("@@rfenghou__shixiao-turn") > 0 and data.card.is_damage_card
  end,
  on_cost = Util.TrueFunc,
  on_use = function(self, event, target, player, data)
    player.room:setPlayerMark(player, "@@rfenghou__shixiao-turn", 0)
    data.disresponsiveList = data.disresponsiveList or {}
    for _, p in ipairs(player.room.alive_players) do
      table.insertIfNeed(data.disresponsiveList, p.id)
    end
  end,
}

shixiao:addRelatedSkill(shixiao_delay) 
caojingzong:addSkill(shixiao) 

Fk:loadTranslationTable{
  [caojingzong.name] = "曹景宗",
  ["#"..caojingzong.name] = "饮锋狂驰",
  ["designer:"..caojingzong.name] = "祭祀",
  ["illustrator:"..caojingzong.name] = "啪啪三国",

  [shixiao.name] = "酾骁",
  [":"..shixiao.name] = "出牌阶段限一次，你可以令本回合下一张伤害牌无法被响应并与任意名角色拼点，赢家：获得所有黑色拼点牌；若你没赢：调整手牌至场上最少，且视为使用因此失去黑色牌数量的【酒】。",
  ["#"..shixiao.name.."_delay"] = "酾骁",

  ["@@"..shixiao.name.."-turn"] = "下张伤害牌强中",
  ["#"..shixiao.name.."-delay"] = "酾骁：您拼点没赢，请弃置手牌至最少，每弃置一张黑色牌便视为使用一张【酒】。",

 --[[
  [shixiao_viewas.name] = "酾骁",
  [":"..shixiao_viewas.name] = "你可以将两/三张牌当一张【杀】/射【杀】使用。",

  [shixiao.name] = "酾骁",
  [":"..shixiao.name] = "出牌阶段限一次，你可以摸三张牌以视为使用【酒】，然后你的手牌每超出1点上限，便将两/三张牌当一张【杀】/射【杀】使用；弃牌阶段，若你未弃置牌，手牌上限-1。",
  [shixiao.name.."-view_as"] = "酾骁：将将两/三张牌当一张【杀】/射【杀】使用%arg",

  [shixiao_negative.name] = "酾骁",
  [":"..shixiao_negative.name] = "弃牌阶段，若你未弃置牌，手牌上限-1。"
  ]]
}

local weirui = General:new(extension, "rfenghou__weirui", "liang", 4)

local huizhuang = fk.CreateActiveSkill{
  name = "rfenghou__huizhuang",
  prompt = function (self)
    return self.name.."-prompt"
  end,
  can_use = function (self, player, card, extra_data)
    return not player:isKongcheng()
  end,
  card_num = 0,
  target_num = 1,
  card_filter = function (self, to_select, selected, player)
    return false
  end,
  target_filter = function (self, to_select, selected, selected_cards, card, extra_data, player)
    return #selected == 0 and to_select ~= player.id
    and not Fk:currentRoom():getPlayerById(to_select):isNude()
  end,
  on_use = function (self, room, effect)
    local player = room:getPlayerById(effect.from)
    local target = room:getPlayerById(effect.tos[1])
    local top_card = room:getNCards(1)
    room:moveCardTo(top_card, Card.Processing, nil, fk.ReasonJustMove, self.name)

    local req = Request:new({player, target}, "AskForUseActiveSkill")
    req.focus_text = self.name
    req.focus_players = {player, target}
    local extraData = {
      "discard_skill",
      "#AskForDiscard:::1:1",
      false,
      {
        num = 1,
        min_num = 1,
        include_equip = 1,
        skillName = self.name,
        pattern = ".",
      },
      false,
    }
    for _, p in ipairs{player, target} do
      req:setData(p, extraData)
    end
    req:ask()

    local cards = {} ---@type integer[][]
    for _, p in ipairs{player, target} do
      local result = req:getResult(p)
      cards[p.id] = result.card.subcards
    end

    room:moveCards({
      ids = cards[player.id],
      from = player.id,
      toArea = Card.DiscardPile,
      moveReason = fk.ReasonDiscard,
      proposer = player.id,
    }, {
      ids = cards[target.id],
      from = target.id,
      toArea = Card.DiscardPile,
      moveReason = fk.ReasonDiscard,
      proposer = target.id,
    })

    local top_num = Fk:getCardById(top_card[1]).number
    local player_num = Fk:getCardById(cards[player.id][1]).number
    local target_num = Fk:getCardById(cards[target.id][1]).number
    local winner
    if math.abs(player_num - top_num) < math.abs(target_num - top_num) then
      winner = player
    elseif math.abs(player_num - top_num) > math.abs(target_num - top_num) then
      winner = target
    end
    if not winner then
      if room:getCardArea(top_card[1]) == Card.Processing then
        room:moveCardTo(top_card, Card.DrawPile, nil, fk.ReasonPut, self.name, nil, true, player.id)
      end
      return
    end

    local all_choices = {
      Fk:translate(self.name.."-use:::"..Fk:getCardById(top_card[1]):toLogString()),
      self.name.."-putToTop", self.name.."-drawAndBreak:"..player.id,
    }

    ---@param chooser ServerPlayer
    ---@param remove_choice string?
    ---@return string
    local doChoose = function (chooser, remove_choice)
      local choices = table.simpleClone(all_choices)
      if not U.getDefaultTargets(chooser, Fk:getCardById(top_card[1])) then
        table.remove(choices, 1)
      end
      if remove_choice and table.contains(choices, remove_choice) then
        table.removeOne(choices, remove_choice)
      end
      if #choices == 0 then return "" end
      return room:askForChoice(chooser, choices, self.name, self.name.."-choice", false, all_choices)
    end

    ---@param proposer ServerPlayer
    ---@param choice string
    local doEffect = function(proposer, choice)
      if choice == all_choices[3] then
        player:drawCards(2)
        room:endTurn()
      elseif choice == all_choices[2] then
        local flag = {card_data = {{Fk:translate(player.general), cards[player.id]}, {Fk:translate(target.general), cards[target.id]}}}
        room:moveCardTo(
          room:askForCardChosen(proposer, proposer, flag, self.name, self.name.."-put"),
          Card.DrawPile, proposer, fk.ReasonPut, self.name, nil, true, proposer.id
        )
      elseif choice == all_choices[1] then
        room:askForUseRealCard(
          proposer, top_card, self.name,
          self.name.."-use:::"..Fk:getCardById(top_card[1]):toLogString(),
          {bypass_times = true, expand_pile = top_card}, false, false
        )
      end
    end

    local choiceA, choiceB
    if winner:isAlive() then
      choiceA = doChoose(winner)
      doEffect(winner, choiceA)
    end
    if player ~= winner then
      if player:isAlive() then
        choiceB = doChoose(player, choiceA)
        doEffect(player, choiceB)
      end
    elseif target:isAlive() then
      choiceB = doChoose(target, choiceA)
      doEffect(target, choiceB)
    end

    if room:getCardArea(top_card[1]) == Card.Processing then
      room:moveCardTo(top_card, Card.DrawPile, nil, fk.ReasonPut, self.name, nil, true, player.id)
    end
  end
}

weirui:addSkill(huizhuang)

Fk:loadTranslationTable{
  [weirui.name] = "韦睿",
  ["#"..weirui.name] = "死绥无却",
  ["designer:"..weirui.name] = "屑",
  ["illustrator:"..weirui.name] = "率土之滨",

  [huizhuang.name] = "麾幢",
  [":"..huizhuang.name] = "出牌阶段，若你有手牌，你可以展示牌堆顶的一张牌，与一名其他角色各弃置一张牌。最靠近展示牌点数的角色选择一项，另一名角色选择另一项："
  .."1.使用展示牌；2.将一张弃置牌置于牌堆顶；3.令你摸两张牌并结束当前回合。",
  [huizhuang.name.."-prompt"] = "是否想发动“麾幢”，展示牌堆顶的一张牌，与一名其他角色各弃置一张牌？",

  [huizhuang.name.."-use"] = "使用%arg",
  [huizhuang.name.."-putToTop"] = "将一张弃置牌置于牌堆顶",
  [huizhuang.name.."-drawAndBreak"] = "令 %src 摸两张牌并结束当前回合",

  [huizhuang.name.."-choice"] = "麾幢：请选择一项",
  [huizhuang.name.."-put"] = "麾幢：将一张弃置牌置于牌堆顶",
}

local yangkan = General:new(extension, "rfenghou__yangkan", "liang", 4)

local lieshu_viewas = fk.CreateViewAsSkill{
  name = "rfenghou__lieshu_viewas",
  interaction = function (self, player)
    local all_choices = self.all_names
    local choices = U.getViewAsCardNames(player, self.name, all_choices)
    return U.CardNameBox{ all_choices = all_choices, choices = choices }
  end,
  view_as = function (self, cards, player)
    if not self.interaction.data then return end
    local card = Fk:cloneCard(self.interaction.data)
    card.skillName = "rfenghou__lieshu"
    return card
  end
}
Fk:addSkill(lieshu_viewas)

local lieshu = fk.CreateTriggerSkill{
  name = "rfenghou__lieshu",
  anim_type = "drawcard",
  events = {fk.EventPhaseEnd},
  can_trigger = function (self, event, target, player, data)
    return player:hasSkill(self) and target.phase == Player.Discard
  end,
  on_cost = function (self, event, target, player, data)
    if #player.room.logic:getEventsOfScope(GameEvent.MoveCards, 1, function (e)
      for _, move in ipairs(e.data) do
        if move.from and move.from == player.id and move.toArea > Card.PlayerEquip then
          for _, info in ipairs(move.moveInfo) do
            if info.fromArea <= Card.PlayerEquip then
              return true
            end
          end
        end
      end
    end, Player.HistoryTurn) == 0 then return end
    local card_num = 0
    player.room.logic:getEventsOfScope(GameEvent.MoveCards, 999, function (e)
      for _, move in ipairs(e.data) do
        if move.proposer == target.id and move.moveReason == fk.ReasonDiscard then
          card_num = card_num + #move.moveInfo
        end
      end
      return false
    end, Player.HistoryPhase)
    local tricks = {}
    for _, card in ipairs(Fk.cards) do
      if not table.contains(player.room.disabled_packs, card.package.name) and not card.is_derived then
        if card.type == Card.TypeTrick and card.sub_type ~= Card.SubtypeDelayedTrick
        and Fk:translate(card.trueName):len() == card_num then
          table.insertIfNeed(tricks, card.name)
        end
      end
    end
    if #tricks == 0 then
      self.cost_data = card_num
      return true
    else
      local _, ret = player.room:askForUseActiveSkill(player, lieshu_viewas.name, self.name.."-view_as", true, {all_names = tricks}, true)
      if ret and ret.interaction and ret.targets then
        local card = Fk:cloneCard(ret.interaction)
        card.skillName = self.name
        self.cost_data = {
          card = card,
          tos = table.map(ret.targets, function(pid) return {pid} end),
          from = player.id,
        }
        return true
      end
    end
  end,
  on_use = function (self, event, target, player, data)
    local cost_data = self.cost_data
    if type(cost_data) == "number" then
      player:drawCards(cost_data)
    else
      player.room:useCard(cost_data)
    end
  end,
}

yangkan:addSkill(lieshu)

Fk:loadTranslationTable{
  [yangkan.name] = "羊侃",
  ["#"..yangkan.name] = "磐城血魄",
  ["designer:"..yangkan.name] = "祭祀",
  ["illustrator:"..yangkan.name] = "率土之滨",

  [lieshu.name] = "烈戍",
  [":"..lieshu.name] = "一名角色的弃牌阶段结束时，若你本回合失去过牌。你可以视为使用一张牌名字数为弃牌数的普通锦囊牌，若无，你摸等量牌。",
  [lieshu.name.."-view_as"] = "烈戍：视为使用一张牌名字数为弃牌数的普通锦囊牌",

  [lieshu_viewas.name] = "烈戍",
  [":"..lieshu_viewas.name] = "你可以视为使用一张牌名字数为弃牌数的普通锦囊牌。",
}

local peisui = General:new(extension, "rfenghou__peisui", "liang", 4)

local updateHuaijingMark = function (player)
  local marks = {}
  if player:getMark("rfenghou__huaijing_suffer-round") > 0 then
    table.insertIfNeed(marks, "受")
  end
  if player:getMark("rfenghou__huaijing_cause-round") > 0 then
    table.insertIfNeed(marks, "造")
  end
  player.room:setPlayerMark(player, "@rfenghou__huaijing-round", table.concat(marks, " "))
end

local huaijing = fk.CreateViewAsSkill{
  name = "rfenghou__huaijing",
  anim_type = "offensive",
  card_num = 1,
  card_filter = function (self, to_select, selected)
    return #selected == 0
  end,
  view_as = function (self, cards, player)
    if #cards == 0 or player:getMark(self.name.."_suffer-round") > 0 then return end
    local card = Fk:cloneCard("duel")
    card.skillName = self.name
    card:addSubcards(cards)
    return card
  end,

  on_acquire = function (self, player, is_start)
    if is_start then return end
    local mark = {}
    player.room.logic:getEventsOfScope(GameEvent.Damage, 999, function (e)
      e.data = e.data ---@type DamageStruct
      if e.data.to == player then
        table.insertIfNeed(mark, self.name.."_suffer-round")
      end
      if e.data.from == player then
        table.insertIfNeed(mark, self.name.."_cause-round")
      end
      return false
    end, Player.HistoryRound)
    for _, m in ipairs(mark) do
      player.room:addPlayerMark(player, m)
    end
    updateHuaijingMark(player)
  end
}

local huaijing_masochism = fk.CreateTriggerSkill{
  name = "#rfenghou__huaijing_masochism",
  anim_type = "masochism",
  events = {fk.Damaged},
  can_trigger = function (self, event, target, player, data)
    return player:hasSkill(huaijing) and player == target and player:getMark(huaijing.name.."_cause-round") == 0
  end,
  on_cost = Util.TrueFunc,
  on_use = function (self, event, target, player, data)
    player:drawCards(2, huaijing.name)
  end
}
huaijing:addRelatedSkill(huaijing_masochism)

local huaijing_refresh = fk.CreateTriggerSkill{
  name = "#rfenghou__huaijing_refresh",
  mute = true,
  refresh_events = {fk.Damage},
  can_refresh = function (self, event, target, player, data)
    return player:hasSkill(huaijing)
  end,
  on_refresh = function (self, event, target, player, data)
    if player == target then
      player.room:addPlayerMark(player, huaijing.name.."_cause-round")
      updateHuaijingMark(player)
    elseif player == data.to then
      player.room:addPlayerMark(player, huaijing.name.."_suffer-round")
      updateHuaijingMark(player)
    end
  end
}
huaijing:addRelatedSkill(huaijing_refresh)

peisui:addSkill(huaijing)

Fk:loadTranslationTable{
  [peisui.name] = "裴邃",
  ["#"..peisui.name] = "韬略伐北",
  ["designer:"..peisui.name] = "祭祀",
  ["illustrator:"..peisui.name] = "率土之滨",

  [huaijing.name] = "怀靖",
  [":"..huaijing.name] = "若你本轮未：受到过伤害，你可以将一张牌当【决斗】使用；造成过伤害，你受到伤害后摸两张牌。",
  [huaijing_masochism.name] = "怀靖",
  [huaijing_refresh.name] = "怀靖",
  [huaijing.name.."_suffer-round"] = "受",
  [huaijing.name.."_cause-round"] = "造",
  ["@"..huaijing.name.."-round"] = "怀靖",
}

local zhuyii = General:new(extension, "rfenghou__zhuyi", "liang", 3)

local qiejun = fk.CreateTriggerSkill{
  name = "rfenghou__qiejun",
  anim_type = "support",
  events = {fk.Damage},
  can_trigger = function (self, event, target, player, data)
    return player:hasSkill(self) and player == target and not player:isNude()
  end,
  on_cost = function (self, event, target, player, data)
    local tos, cards = player.room:askForChooseCardsAndPlayers(
      player, 1, 999, table.map(player.room:getOtherPlayers(player, false), Util.IdMapper), 1, 1,
      ".", self.name.."-give", self.name, true
    )
    if #tos == 1 and #cards > 0 then
      self.cost_data = {cards, tos[1], #cards == #player:getCardIds("he")}
      return true
    end
  end,
  on_use = function (self, event, target, player, data)
    local cards, to, reveal = table.unpack(self.cost_data)
    player.room:moveCards{
      ids = cards,
      from = player.id,
      to = to,
      toArea = Card.PlayerHand,
      moveReason = fk.ReasonGive,
      skillName = self.name,
      proposer = player.id,
    }
    if player:isAlive() and player:isWounded() then
      player.room:recover{
        who = player,
        num = 1,
        recoverBy = player,
        skillName = self.name,
      }
    end
  end
}

local qiejun_masochism = fk.CreateTriggerSkill{
  name = "#rfenghou__qiejun_masochism",
  anim_type = "masochism",
  events = {fk.Damaged},
  can_trigger = function (self, event, target, player, data)
    return player:hasSkill(qiejun) and player == target and not player:isNude()
  end,
  on_cost = function (self, event, target, player, data)
    local cards = player.room:askForDiscard(player, 1, 999, true, qiejun.name, true, ".", qiejun.name.."-discard", true)
    if #cards > 0 then
      self.cost_data = {cards, #cards == #player:getCardIds("he")}
      return true
    end
  end,
  on_use = function (self, event, target, player, data)
    local cards, draw = table.unpack(self.cost_data)
    player.room:throwCard(cards, qiejun.name, player, player)
    if player:isAlive() and player:getHandcardNum() < player.maxHp and draw then
      player:drawCards(player.maxHp - player:getHandcardNum(), qiejun.name)
    end
  end
}
qiejun:addRelatedSkill(qiejun_masochism)

zhuyii:addSkill(qiejun)

---@param id integer
---@return boolean
local isImmediate = function (id)
  return Fk:getCardById(id).type == Card.TypeBasic or Fk:getCardById(id):isCommonTrick()
end

local chanyan = fk.CreateViewAsSkill{
  name = "rfenghou__chanyan",
  anim_type = "negative",
  pattern = ".",
  prompt = function (self, selected_cards, selected)
    if #selected_cards == 0 then
      return self.name.."view_as"
    else
      return self.name.."sub"
    end
  end,
  card_num = 2,
  card_filter = function (self, to_select, selected, player)
    if #selected == 0 then
      local temple = Fk:cloneCard(Fk:getCardById(to_select).name)
      temple.skillName = self.name
      return player:canUse(temple) and isImmediate(to_select)
    elseif #selected == 1 then
      return isImmediate(to_select)
    else
      return false
    end
  end,
  view_as = function (self, cards, player)
    if #cards ~= 2 then return end
    local card, sub = table.unpack(cards)
    local _card = Fk:cloneCard(Fk:getCardById(card).name)
    _card.skillName = self.name
    _card:addSubcards(cards)
    return _card
  end,
  enabled_at_play = function (self, player)
    return player:getMark("@@rfenghou__chanyan-phase") == 1
  end,

  before_use = function (self, player, use)
    if not use.tos then return end
    local extra = table.filter(player.room:getAlivePlayers(false), function (p)
      return not TargetGroup:includeRealTargets(use.tos, p.id)
    end)
    if #extra == 0 then return end
    local to = player.room:askForChoosePlayers(
      player, table.map(extra, Util.IdMapper), 1, 1,
      self.name.."extra:::"..use.card:toLogString(), self.name, true
    )
    if #to == 1 then
      TargetGroup:pushTargets(use.tos, to[1])
    end
  end,
}

local chanyan_trigger = fk.CreateTriggerSkill{
  name = "#rfenghou__chanyan_trigger",
  anim_type = "drawcard",
  events = {fk.EventPhaseStart},
  can_trigger = function (self, event, target, player, data)
    return player:hasSkill(chanyan) and player == target and player.phase == Player.Play
  end,
  on_use = function (self, event, target, player, data)
    player:drawCards(3, chanyan.name)
    player.room:setPlayerMark(player, "@@rfenghou__chanyan-phase", 1)
  end
}
chanyan:addRelatedSkill(chanyan_trigger)

local chanyan_prohibit = fk.CreateProhibitSkill{
  name = "#rfenghou__chanyan_prohibit",
  prohibit_use = function (self, player, card)
    if player:getMark("@@rfenghou__chanyan-phase") == 1 then
      return not table.contains(card.skillNames, chanyan.name)
    end
  end,
}
chanyan:addRelatedSkill(chanyan_prohibit)

zhuyii:addSkill(chanyan)

Fk:loadTranslationTable{
  [zhuyii.name] = "朱异",
  ["#"..zhuyii.name] = "祸国弈枢",
  ["designer:"..zhuyii.name] = "祭祀",
  ["illustrator:"..zhuyii.name] = "啪啪三国",

  [qiejun.name] = "窃钧",
  [":"..qiejun.name] = "你造成伤害后，可以交出任意张牌，若含最后一张，回复1点体力；你受到伤害后，可以弃置任意张牌，若含最后一张，摸牌至体力上限。",
  [qiejun_masochism.name] = "窃钧",
  [qiejun.name.."-give"] = "窃钧：可以交出任意张牌，若含最后一张，回复1点体力",
  [qiejun.name.."-discard"] = "窃钧：可以弃置任意张牌，若含最后一张，摸牌至体力上限",

  [chanyan.name] = "谗焰",
  [":"..chanyan.name] = "出牌阶段开始时，你可以摸三张牌，令本阶段你仅能将两张即时牌当其中一张牌使用，且以此牌可多选择一个目标（无视合法性）。",
  [chanyan_trigger.name] = "谗焰",
  [chanyan_prohibit.name] = "谗焰",
  ["@@rfenghou__chanyan-phase"] = "谗焰",
  [chanyan.name.."view_as"] = "谗焰：两张即时牌当其中一张牌使用，选择要使用的牌（1/2）",
  [chanyan.name.."sub"] = "谗焰：两张即时牌当其中一张牌使用，选择底牌（2/2）",
  [chanyan.name.."extra"] = "谗焰：可以为 %arg 多选择一个目标（无视合法性）",
}

local xiahouxiang = General:new(extension, "rfenghou__xiahouxiang", "liang", 3)
xiahouxiang.total_hidden = true -- 应祭祀要求，夏侯详封存，技能组转移到谢蘅传

local anyu_cards = {[Card.Heart] = "fire_attack", [Card.Spade] = "drowning"}

local anyu = fk.CreateViewAsSkill{
  name = "rfenghou__anyu",
  anim_type = "offensive",
  card_filter = function (self, to_select, selected, player)
    if #selected ~= 0 then return false end
    return anyu_cards[Fk:getCardById(to_select).suit] ~= nil
  end,
  view_as = function (self, cards, player)
    if #cards ~= 1 then return end
    local card = Fk:getCardById(cards[1])
    local _card = Fk:cloneCard(anyu_cards[card.suit])
    _card.skillName = self.name
    _card:addSubcards(cards)
    return _card
  end,
  after_use = function (self, player, use)
    if player:getMark("rfenghou__anyu") == 1 then
      player.room:setPlayerMark(player, "rfenghou__anyu", 0)
      player.room:useVirtualCard("ex_nihilo", nil, player, player, self.name)
    end
  end,
  enabled_at_play = function (self, player)
    return player.phase == Player.Play
    and player:usedSkillTimes(self.name, Player.HistoryPhase) == 0
  end,
  enabled_at_response = Util.FalseFunc,
}
local anyu_delay = fk.CreateTriggerSkill{
  name = "#rfenghou__anyu-delay",

  refresh_events = {fk.AfterCardsMove},
  can_refresh = function(self, event, target, player, data)
    if not player.dead then
      for _, move in ipairs(data) do
        if move.toArea == Card.DiscardPile and move.moveReason == fk.ReasonDiscard and
          table.contains({"drowning_skill", "fire_attack_skill"}, move.skillName) then
          local use_event = player.room.logic:getCurrentEvent():findParent(GameEvent.UseCard)
          if use_event then
            local use = use_event.data[1] ---@type CardUseStruct
            if use.from == player.id then
              return true
            end
          end
        end
      end
    end
  end,
  on_refresh = function(self, event, target, player, data)
    player.room:addTableMarkIfNeed(player, "rfenghou__anyu", 1)
  end,
}
anyu:addRelatedSkill(anyu_delay)

--xiahouxiang:addSkill(anyu)

-- local shengxi = fk.CreateTriggerSkill{
--   name = "rfenghou__shengxi",
--   anim_type = "drawcard",
--   events = {fk.EventPhaseStart},
--   can_trigger = function (self, event, target, player, data)
--     if player:hasSkill(self) and player == target and player.phase == Player.Finish then
--       return #player.room.logic:getActualDamageEvents(1, function (e)
--         return e.data.from and e.data.from == player
--       end, Player.HistoryTurn) == 0
--     end
--   end,
--   on_cost = Util.TrueFunc,
--   on_use = function (self, event, target, player, data)
--     player:drawCards(2, self.name)
--   end
-- }
-- xiahouxiang:addSkill(shengxi)

--xiahouxiang:addSkill("rfenghou__shengxi")

Fk:loadTranslationTable{
  [xiahouxiang.name] = "夏侯详",
  ["#"..xiahouxiang.name] = "砥柱镇后",
  ["designer:"..xiahouxiang.name] = "祭祀",

  -- [anyu.name] = "安舆",
  -- [":"..anyu.name] = "出牌阶段限一次，你可以将一张<font color='red'>♥</font>牌当【火攻】或♠牌当【水淹七军】使用，若有角色因此弃置牌，你视为使用【无中生有】。",
  -- [anyu_delay.name] = "安舆",

  -- [shengxi.name] = "生息",
  -- [":"..shengxi.name] = "结束阶段，若你本回合未造成伤害，你摸两张牌。"
}

local chenqingzhi = General:new(extension, "rfenghou__chenqingzhi", "liang", 4)

local lueshi = fk.CreateViewAsSkill{
  name = "rfenghou__lueshi",
  anim_type = "special",
  interaction = function (self, player)
    local all_choices = {}
    for _, card in ipairs(Fk.cards) do
      if not table.contains(Fk:currentRoom().disabled_packs, card.package.name) and not card.is_derived then
        if card.type == Card.TypeTrick and card.sub_type ~= Card.SubtypeDelayedTrick and not card.multiple_targets then
          table.insertIfNeed(all_choices, card.name)
        end
      end
    end
    local choices = U.getViewAsCardNames(player, self.name, all_choices)
    return U.CardNameBox {all_choices = all_choices, choices = choices}
  end,
  card_filter = Util.FalseFunc,
  view_as = function (self, cards, player)
    if not self.interaction.data then return end
    local card = Fk:cloneCard(self.interaction.data)
    card.skillName = self.name
    return card
  end,
  enabled_at_play = function (self, player)
    return player.phase == Player.Play
    and player:usedSkillTimes(self.name, Player.HistoryPhase) == 0
  end,
}

local lueshi_delay = fk.CreateTriggerSkill{
  name = "#rfenghou__lueshi_delay",
  anim_type = "support",
  events = {fk.CardUseFinished},
  can_trigger = function (self, event, target, player, data)
    if player:hasSkill(lueshi) and player:usedSkillTimes(lueshi.name, Player.HistoryPhase) > 0 then
      return data.card.type == Card.TypeBasic and target == player
      and player:getMark("@@rfenghou__lueshi-turn") == 0
    end
  end,
  on_cost = Util.TrueFunc,
  on_use = function (self, event, target, player, data)
    player:setSkillUseHistory(lueshi.name, 0, Player.HistoryPhase)
  end,
}
lueshi:addRelatedSkill(lueshi_delay)

local lueshi_prohibit = fk.CreateTriggerSkill{
  name = "#rfenghou__lueshi_prohibit",
  anim_type = "negative",

  refresh_events = {fk.AfterCardsMove},
  can_refresh = function (self, event, target, player, data)
    if player:hasSkill(lueshi) and player:usedSkillTimes(lueshi.name, Player.HistoryPhase) > 0 then
      for _, move in ipairs(data) do
        if move.to == player.id and move.toArea == Card.PlayerHand then
          return #move.moveInfo > 0
        end
      end
    end
  end,
  on_refresh = function (self, event, target, player, data)
    player.room:setPlayerMark(player, "@@rfenghou__lueshi-turn", 1)
  end
}
lueshi:addRelatedSkill(lueshi_prohibit)

chenqingzhi:addSkill(lueshi)

Fk:loadTranslationTable{
  [chenqingzhi.name] = "陈庆之",
  ["#"..chenqingzhi.name] = "挥白染旌",
  ["designer:"..chenqingzhi.name] = "凡野",
  ["illustrator:"..chenqingzhi.name] = "率土之滨",

  [lueshi.name] = "略师",
  [":"..lueshi.name] = "出牌阶段限一次，你可以视为使用一张目标唯一的普通锦囊牌。若你本阶段发动过本技能：你使用基本牌后，重置此技能；你获得牌后，本技能本回合无法以上述方式重置。",
  [lueshi_delay.name] = "略师",
  [lueshi_prohibit.name] = "略师",
  ["@@rfenghou__lueshi-turn"] = "略师",

}

local maxianbing = General:new(extension, "rfenghou__maxianbing", "liang", 4)

local liequ = fk.CreateTriggerSkill{
  name = "rfenghou__liequ",
  events = {fk.TargetSpecifying, fk.CardUseFinished},
  can_trigger = function(self, event, target, player, data)
    if event == fk.TargetSpecifying then
      return player:hasSkill(self) and data.card.trueName == "slash" and data.firstTarget and target ~= player and
      #table.filter(AimGroup:getAllTargets(data.tos), function (id) return player:inMyAttackRange(player.room:getPlayerById(id)) end) > 0
      and not table.contains(AimGroup:getAllTargets(data.tos), player.id)
    elseif event == fk.CardUseFinished then
      return data.extra_data and ((data.extra_data.rfenghou__liequ1 and table.contains(data.extra_data.rfenghou__liequ1, player.id)) or
      (data.extra_data.rfenghou__liequ2 and table.contains(data.extra_data.rfenghou__liequ2, player.id)))
    end
  end,
  on_cost = function(self, event, target, player, data)
    local room = player.room
    if event == fk.TargetSpecifying then
      return room:askForSkillInvoke(player, self.name, nil, "#rfenghou__liequ-invoke")
    elseif event == fk.CardUseFinished then
      return true
    end
  end,
  on_use = function(self, event, target, player, data)
    local room = player.room
    if event == fk.TargetSpecifying then
      local choices = {"liequ_before","liequ_after"}
      local choice = room:askForChoice(player, choices, self.name, "#rfenghou__liequ-choice")
      AimGroup:addTargets(room, data, player.id)
      AimGroup:setTargetDone(data.tos, player.id)
      if choice == "liequ_before" then
        data.extra_data = data.extra_data or {}
        data.extra_data.rfenghou__liequ1 = data.extra_data.rfenghou__liequ1 or {}
        table.insert(data.extra_data.rfenghou__liequ1, player.id)
      elseif choice == "liequ_after" then
        data.extra_data = data.extra_data or {}
        data.extra_data.rfenghou__liequ2 = data.extra_data.rfenghou__liequ2 or {}
        table.insert(data.extra_data.rfenghou__liequ2, player.id)
      end
    elseif event == fk.CardUseFinished then
      if data.extra_data and data.extra_data.rfenghou__liequ1 and table.contains(data.extra_data.rfenghou__liequ1, player.id) then
        if data.extra_data and data.extra_data.rfenghou__liequ1_list and #data.extra_data.rfenghou__liequ1_list > 0 then
          for _, p in ipairs (data.extra_data.rfenghou__liequ1_list) do
            if room:getPlayerById(p):isWounded() and not room:getPlayerById(p).dead then
              room:recover { num = 1, skillName = self.name, who = room:getPlayerById(p), recoverBy = room:getPlayerById(p) }
            end
          end
        end
      end
      if data.extra_data and data.extra_data.rfenghou__liequ2 and table.contains(data.extra_data.rfenghou__liequ2, player.id) then
        if data.extra_data and data.extra_data.rfenghou__liequ2_list and #data.extra_data.rfenghou__liequ2_list > 0 then
          for _, p in ipairs (data.extra_data.rfenghou__liequ2_list) do
            if not room:getPlayerById(p).dead and not target.dead then
              room:damage{ from = room:getPlayerById(p), to = target, damage = 1, skillName = self.name }
            end
          end
        end
      end
    end
  end,

  refresh_events = {fk.CardUseFinished, fk.Damaged},
  can_refresh = function(self, event, target, player, data)
    if event == fk.CardUseFinished then
      return data.responseToEvent and data.responseToEvent.extra_data and data.responseToEvent.extra_data.rfenghou__liequ1
      and table.contains(data.responseToEvent.extra_data.rfenghou__liequ1, player.id)
      and not table.contains(data.responseToEvent.extra_data.rfenghou__liequ1_stop or {}, player.id)
    elseif event == fk.Damaged then
      if data.card == nil then return false end
      local card_event = player.room.logic:getCurrentEvent():findParent(GameEvent.UseCard)
      if not card_event then return false end
      local use = card_event.data[1]
      return use.damageDealt and use.damageDealt[player.id] and target ~= player and
      use.extra_data and use.extra_data.rfenghou__liequ2 and table.contains(use.extra_data.rfenghou__liequ2, player.id)
      and not table.contains(use.extra_data.rfenghou__liequ2_list or {}, target.id)
    end
  end,
  on_refresh = function(self, event, target, player, data)
    local room = player.room
    if event == fk.CardUseFinished then
      if target ~= player then
        data.responseToEvent.extra_data = data.responseToEvent.extra_data or {}
        data.responseToEvent.extra_data.rfenghou__liequ1_list = data.responseToEvent.extra_data.rfenghou__liequ1_list or {}
        table.insert(data.responseToEvent.extra_data.rfenghou__liequ1_list, target.id)
      elseif target == player then
        data.responseToEvent.extra_data = data.responseToEvent.extra_data or {}
        data.responseToEvent.extra_data.rfenghou__liequ1_stop = data.responseToEvent.extra_data.rfenghou__liequ1_stop or {}
        table.insert(data.responseToEvent.extra_data.rfenghou__liequ1_stop, player.id)
      end
    elseif event == fk.Damaged then
      local card_event = room.logic:getCurrentEvent():findParent(GameEvent.UseCard)
      if not card_event then return false end
      local use = card_event.data[1]
      if use.damageDealt and use.damageDealt[player.id] and target ~= player
      and use.extra_data and use.extra_data.rfenghou__liequ2 and table.contains(use.extra_data.rfenghou__liequ2, player.id) then
        use.extra_data = use.extra_data or {}
        use.extra_data.rfenghou__liequ2_list = use.extra_data.rfenghou__liequ2_list or {}
        table.insert(use.extra_data.rfenghou__liequ2_list, target.id)
      end
    end
  end,
}

Fk:loadTranslationTable{
  [maxianbing.name] = "马仙琕",
  ["#"..maxianbing.name] = "蹈义全节",
  ["designer:"..maxianbing.name] = "张让",
  ["illustrator:"..maxianbing.name] = "啪啪三国",

  [liequ.name] = "烈驱",
  [":"..liequ.name] = "你攻击范围内的角色成为【杀】的目标时，你可以成为额外目标并选择一项于此牌结算后执行：早于你响应此牌的角色回复1点体力；晚于你受到此牌伤害的角色对使用者造成1点伤害。",

  ["liequ_before"] = "早于你响应此牌的角色回复1点体力",
  ["liequ_after"] = "晚于你受到此牌伤害的角色对使用者造成1点伤害",
  ["#"..liequ.name.."-invoke"] = "烈驱：是否成为此【杀】额外目标？若是，你可以令比你早响应或比你晚受到伤害的角色获得增益！",
  ["#"..liequ.name.."-choice"] = "烈驱：请选择一项于此【杀】结算后执行！",
}

maxianbing:addSkill(liequ)
maxianbing:addSkill("mashu")

local xiaoqingzhou = General:new(extension, "rfenghou__xiaoqingzhou", "liang", 3, 3, General.Female)

local bingchun = fk.CreateTriggerSkill{
  name = "rfenghou__bingchun",
  anim_type = "masochism",
  events = {fk.Damaged},
  can_trigger = function(self, event, target, player, data)
    if player ~= target or not player:hasSkill(self) then return false end
    local room = player.room
    local damage_event = room.logic:getCurrentEvent()
    if not damage_event then return false end
    local x = 0
    room.logic:getEventsOfScope(GameEvent.ChangeHp, 999, function (e)
      if e.data[1] == player and e.data[3] == "damage" then
        x = x + 1
      end
    end, Player.HistoryTurn)
    room:setPlayerMark(player, "@rfenghou__bingchun-turn", x)
    return player:getMark("@rfenghou__bingchun-turn") == 1 or data.damageType ~= fk.NormalDamage
  end,
  on_use = function(self, event, target, player, data)
    local room = player.room
    local recover = false
    local draw = false
    if data.damageType ~= fk.NormalDamage then
      recover = true
    end
    if player:getMark("@rfenghou__bingchun-turn") == 1 then
      draw = true
    end
    if recover and not player.dead then
      room:recover{
        who = player,
        num = 1,
        recoverBy = player,
        skillName = self.name
      }
    end
    if draw and not player.dead then
      player:drawCards(1, self.name)
    end
    if draw and recover and not player.dead then
      room:addPlayerMark(player, MarkEnum.AddMaxCards, 1)
    end
  end
}

xiaoqingzhou:addSkill(bingchun)

local feixue_viewas = fk.CreateViewAsSkill{
  name = "rfenghou__feixue_viewas",
  min_card_num = 2,
  max_card_num = 3,
  card_filter = function (self, to_select, selected, player)
    return #selected < 3
  end,
  view_as = function (self, cards, player)
    local card_name
    if #cards == 2 then
      card_name = "slash"
    elseif #cards == 3 then
      card_name = "rfenghou_shoot__slash"
    else
      return nil
    end
    local card = Fk:cloneCard(card_name)
    card.skillName = self.name
    card:addSubcards(cards)
    return card
  end
}
Fk:addSkill(feixue_viewas)

local feixue = fk.CreateTriggerSkill{
  name = "rfenghou__feixue",
  anim_type = "control",
  events = {fk.EventPhaseEnd},
  can_trigger = function(self, event, target, player, data)
    return target == player and player:hasSkill(self) and player.phase == Player.Play and player:getHandcardNum() < player:getMaxCards()
  end,
  on_use = function(self, event, target, player, data)
    local room = player.room
    room:addPlayerMark(player, MarkEnum.MinusMaxCards, 1)
    player:drawCards(3, self.name)
    if not player:isAlive() or #player:getCardIds("he") < 2
    or not U.getDefaultTargets(player, Fk:cloneCard("rfenghou_shoot__slash"), true) then
      return false
    end
    local _, ret = room:askForUseActiveSkill(
      player, feixue_viewas.name,
      "#"..feixue_viewas.name,
      false, { bypass_times = true, extraUse = true }
    )
    if ret and ret.cards and ret.targets then
      local card_name
      if #ret.cards == 2 then
        card_name = "slash"
      elseif #ret.cards == 3 then
        card_name = "rfenghou_shoot__slash"
      end
      local card = Fk:cloneCard(card_name)
      card.skillName = self.name
      card:addSubcards(ret.cards)
      room:useCard{
        card = card,
        tos = table.map(ret.targets, function(pid) return {pid} end),
        from = player.id
      }
    end
  end,
}

xiaoqingzhou:addSkill(feixue)

Fk:loadTranslationTable{
  [xiaoqingzhou.name] = "萧清昼",
  ["illustrator:"..xiaoqingzhou.name] = "率土之滨",
  ["designer:"..xiaoqingzhou.name] = "祭祀",

  [bingchun.name] = "冰春",
  [":"..bingchun.name] = "你受到伤害后，若为本回合首次，可以摸一张牌，若为属性伤害，可以回复1点体力，若均满足，加1点手牌上限。",
  [feixue.name] = "绯血",
  [":"..feixue.name] = "出牌阶段结束时，若你手牌少于手牌上限，你可以失去1点手牌上限并摸三张牌，然后将两/三张牌当一张【杀】/射【杀】使用。"..
  "<br><a href='rfenghou__xiaoqingzhou_story_href'>萧清昼生平简介</a>",

  ["@"..bingchun.name.."-turn"] = "冰春",
  [feixue_viewas.name] = "绯血",
  [":"..feixue_viewas.name] = "你需将两/三张牌当一张【杀】/射【杀】使用。",
  ["#"..feixue_viewas.name] = "你需将两/三张牌当一张【杀】/射【杀】使用。",
  
  ["rfenghou__xiaoqingzhou_story_href"] = "萧氏清昼，小字醁醽，南梁天监年间人也。其祖乃前朝宗室，父镇北将军萧琰，母为北朝乐伎苏摩儿。永元元年，琰因谏佛寺圈地事触怒权贵，贬谪建康，"..
  "遂携妻隐于秦淮河曲，鬻酒为生，匾曰“醉南朝”。<br>清昼生具异禀，三岁能辨醴泉甘苦，七岁以青梅入酒，得梁武帝赐名“冰髓春”。然其性桀骜，尝醉书永宁寺粉壁：“佛骨岂如酒骨香，袈裟不染胭脂红”，"..
  "满城哗然。时有还俗僧法镜者，夜叩酒肆，以铁琵琶奏《凉州破阵曲》，清昼闻之落泪——此曲乃其母临终绝响，竟于廿载后复闻江南。<br>年十七，逢寒士裴昭光赴考。二人幼时曾埋双耳壶于桃根，"..
  "誓待琼林宴罢同饮。然昭光及第之日，东宫忽遣使索“般若汤”。此酒以优昙花、砗磲粉酿之，饮者见琉璃净土，实为佛道相争之秘药。酒成那夜地动山摇，钦天监奏曰：“酒气冲犯太微垣”，禁军围肆，"..
  "火光中见昭光绯袍染血，怀中露半角羊皮，隐约现“萧氏通魏”四字。<br>清昼长笑掷坛，琥珀酒泼作漫天星雨。或传其踏碎玉铃铛遁去，秦淮河畔空余酒幡招摇，上书“醉里乾坤大，壶中日月长”。",
}

local xieheng = General:new(extension, "rfenghou__xieheng", "liang", 3, 3, General.Female)

xieheng:addSkill(anyu)
xieheng:addSkill("rfenghou__shengxi")

Fk:loadTranslationTable{
  [xieheng.name] = "谢蘅",
  ["illustrator:"..xieheng.name] = "率土之滨",
  ["designer:"..xieheng.name] = "祭祀",

  [anyu.name] = "安舆",
  [":"..anyu.name] = "出牌阶段限一次，你可以将一张<font color='red'>♥</font>牌当【火攻】或♠牌当【水淹七军】使用，若有角色因此弃置牌，你视为使用【无中生有】。"..
  "<br><a href='rfenghou__xieheng_story_href'>谢蘅传生平简介</a>",
  [anyu_delay.name] = "安舆",
  
  ["rfenghou__xieheng_story_href"] = "谢氏蘅，字含章，生于南梁大同年间，丹阳秣陵人。其祖谢纬官至司农卿，尝制《劝农十二策》。蘅幼失怙恃，养于鸡笼山农庄，夜观星象知晴雨，"..
  "晨辨土色断丰歉，乡人呼为“小稷神”。<br>普通七年，江左大蝗。蘅取古法改良，造连机水碓九转筛，分蝗为四等：活虫饲鸭、死虫入药、虫卵焙肥、翅粉制烛。更作《生息图说》，绘蝗虫化灰沃土之景，"..
  "老农观图而悟：“死生相续，方为天道”。建康令闻之，命其督造“生息渠”，引玄武湖水灌三千亩焦田。蘅立渠畔七日，发间缀满稻花，指节缠绕菖蒲，谓众人曰：“地脉如人经络，淤塞处当以生气贯之。”"..
  "<br>太清二年，侯景围台城。蘅携农人夜掘地道，暗输麦种入城。守军见麦粒刻“生”字者，皆含泪吞服——此乃蘅用茜草根汁浸种之术，三日即发麦苗二寸，暂缓饥馑。城破那日，有人见青衣女子散稻种于"..
  "御道裂石间，经年竟成碧浪，鸟雀啄穗时，空中隐有《齐民要术》吟诵声。<br>后世田间祭“生息娘子”，神像左手执穗，右手握半截残碑，上镌十六字真言：“土养魂兮苗养身，死中求活是真春”。",
}

local xihui = General:new(extension, "rfenghou__xihui", "liang", 3, 3, General.Female)
xihui.hidden = true

Fk:loadTranslationTable{
  [xihui.name] = "郗徽",
  ["#"..xihui.name] = "虚凤承天",
  ["illustrator:"..xihui.name] = "夏信",
  ["designer:"..xihui.name] = "祭祀&屑",

  --[jiaoaii.name] = "椒哀",
  --[":"..jiaoaii.name] = "一名角色受到伤害后，你可令其摸一/两张牌，然后伤害来源可令你摸两/一张牌。你以此摸牌后，须翻面或失去1点体力，且若会摸至唯一最多，则均执行。",
  --[luanjii.name] = "鸾寂",
  --[":"..luanjii.name] = "锁定技，一名角色手牌数或体力值首次等于其本回合发动技能次数时，其摸一张牌。若再次相等，你回复1点体力或手牌上限+1。",
}

local shenyue = General:new(extension, "rfenghou__shenyue", "liang", 3, 3, General.Male)

local luomoo = fk.CreateTriggerSkill{
  name = "rfenghou__luomoo",
  anim_type = "support",
  events = {fk.CardUseFinished},
  can_trigger = function(self, event, target, player, data)
    local current = table.find(player.room.alive_players, function(p) return p.phase ~= Player.NotActive end)
    return current and target == current and player:hasSkill(self) and player.room:getCardArea(data.card) == Card.Processing and
      data.card.suit == Card.Club and player:usedSkillTimes(self.name, Player.HistoryTurn) == 0
  end,
  on_cost = function(self, event, target, player, data)
    local current = table.find(player.room.alive_players, function(p) return p.phase ~= Player.NotActive end)
    if current == nil then return end
    return player.room:askForSkillInvoke(player, self.name, data, "#rfenghou__luomoo-choose:::"..current.general..":"..data.card:toLogString())
  end,
  on_use = function(self, event, target, player, data)
    local current = table.find(player.room.alive_players, function(p) return p.phase ~= Player.NotActive end)
    if current then
      player.room:obtainCard(current.id, data.card, true, fk.ReasonPrey, player.id, self.name)
    end
  end,
}
shenyue:addSkill(luomoo)

local yongmingg = fk.CreateTriggerSkill{
  name = "rfenghou__yongmingg",
  events = {fk.CardUseFinished, fk.CardRespondFinished},
  can_trigger = function(self, event, target, player, data)
    return target == player and player:hasSkill(self) and player.room:getCardArea(data.card) == Card.Processing and
    data.card.suit == Card.Diamond and player:usedSkillTimes(self.name, Player.HistoryRound) == 0
  end,
  on_use = function(self, event, target, player, data)
    player.room:obtainCard(player.id, data.card, true, fk.ReasonPrey, player.id, self.name)
  end,
}
shenyue:addSkill(yongmingg)

Fk:loadTranslationTable{
  [shenyue.name] = "沈约",
  ["#"..shenyue.name] = "暂无",
  ["illustrator:"..shenyue.name] = "啪啪三国",
  ["designer:"..shenyue.name] = "君腾天下",

  [luomoo.name] = "落墨",
  [":"..luomoo.name] = "每回合限一次，当前回合角色使用的♣牌结算完后，你可令其获得之。",
  ["#"..luomoo.name.."-choose"] = "落墨：是否令 %arg 获得 %arg2 ？",
  [yongmingg.name] = "永明",
  [":"..yongmingg.name] = "每轮限一次，你使用或打出的<font color='red'>♦</font>牌结算完后，你可获得之。",
}

local xiaotong = General:new(extension, "rfenghou__xiaotong", "liang", 3, 3, General.Male)

local llinli = fk.CreateTriggerSkill{
  name = "rfenghou__llinli",
  anim_type = "support",
  events = {fk.AfterCardsMove},
  can_trigger = function(self, event, target, player, data)
    if player:hasSkill(self) then
      local list = {}
      for _, move in ipairs(data) do
        if move.toArea == Card.DiscardPile and #move.moveInfo > 1 then
          for _, info in ipairs(move.moveInfo) do
            if Fk:getCardById(info.cardId).type == Card.TypeTrick then
              table.insert(list, info.cardId)
            end
          end
        end
      end
      if #list >= 2 then
        self.cost_data = {list}
        return true
      end
    end
  end,
  on_use = function(self, event, target, player, data)
    local currentEvent = player.room.logic:getCurrentEvent()
    local lastEvent = player.room.logic:getEventsByRule(GameEvent.SkillEffect, 1, function (e)
      return e.id < currentEvent.id and e.data[2] == player and e.data[3]:isPlayerSkill(player) and e.data[3].visible
    end, 1)[1]
    if lastEvent then
      local last = lastEvent.data[3]
      last = (last.main_skill or last)
      if last == Fk.skills["rfenghou__llinli"] then
        local cards = table.filter(player:getCardIds("h"), function (id)
          return Fk:getCardById(id):getMark("@@rfenghou__llinli-inhand") > 0
        end)
        local card = player.room:askForCard(player, 1, 1, false, self.name, false, tostring(Exppattern{ id = cards }), "#rfenghou__llinli-discard")
        player.room:throwCard(card, self.name, player, player)
      end
    end
    local handcard = {}
    local list = self.cost_data[1]
    for _, id in ipairs (player:getCardIds("h")) do --展示前要先插入卡牌id数组，因为你扶真有展示牌后把牌挪走的
      table.insertIfNeed(handcard, id)
    end
    if not player:isKongcheng() then
      player:showCards(player:getCardIds("h"))
    end
    local get = true
    for _, id in ipairs (handcard) do
      if table.find(list, function(p) return Fk:getCardById(id).number >= Fk:getCardById(p).number end) then
        get = false
        break
      end
    end
    if get and not player.dead then
      local choices = {"rfenghou__llinli-takeall","cancel"}
      local choice = player.room:askForChoice(player, choices, self.name, "#rfenghou__llinli-choice")
      if choice == "rfenghou__llinli-takeall" then
      for _, id in ipairs (player:getCardIds("h")) do
        player.room:setCardMark(Fk:getCardById(id), "@@rfenghou__llinli-inhand", 0)
      end
      player.room:obtainCard(player.id, list, true, fk.ReasonPrey, player.id, self.name, "@@rfenghou__llinli-inhand")
      end
    end
  end,
}
xiaotong:addSkill(llinli)

local ffuxing = fk.CreateTriggerSkill{
  name = "rfenghou__ffuxing",
  events = {fk.EventPhaseEnd},
  can_trigger = function(self, event, target, player, data)
    if target ~= player and player:hasSkill(self) and target.phase == Player.Discard 
    and player:usedSkillTimes(self.name, Player.HistoryTurn) == 0 then
      local room = player.room
      local ffuxing_hand, cards = {}, {}
      local phase_event = room.logic:getCurrentEvent():findParent(GameEvent.Phase, true)
      if phase_event == nil then return false end
      local end_id = phase_event.id
      room.logic:getEventsByRule(GameEvent.MoveCards, 1, function (e)
        for _, move in ipairs(e.data) do
          for _, info in ipairs(move.moveInfo) do
            local id = info.cardId
            if not table.contains(cards, id) then
              table.insert(cards, id)
              if move.toArea == Card.DiscardPile and move.moveReason == fk.ReasonDiscard and
                room:getCardArea(id) == Card.DiscardPile then
                if move.from == target.id and info.fromArea == Card.PlayerHand then
                  table.insert(ffuxing_hand, id)
                end
              end
            end
          end
        end
        return false
      end, end_id)
      if #ffuxing_hand >= 0 then
        self.cost_data = {ffuxing_hand}
        return true
      end
    end
  end,
  on_use = function(self, event, target, player, data)
    local list = {}
    local ffuxing_hand = self.cost_data[1]
    for _, id in ipairs (player:getCardIds("h")) do --展示前要先插入卡牌id数组，因为你扶真有展示牌后把牌挪走的
      table.insertIfNeed(list, id)
    end
    if not player:isKongcheng() then
      player:showCards(player:getCardIds("h"))
    end
    if #ffuxing_hand == 0 then return end
    local get = true
    for _, id in ipairs (list) do
      if table.find(ffuxing_hand, function(p) return Fk:getCardById(id).trueName == Fk:getCardById(p).trueName end) then
        get = false
        break
      end
    end
    if get and not player.dead then
      local min = 13
      for _, id in ipairs(ffuxing_hand) do
        if Fk:getCardById(id).number < min then
          min = Fk:getCardById(id).number
        end
      end
      local getlist = {}
      for i = #ffuxing_hand, 1, -1 do
        if Fk:getCardById(ffuxing_hand[i]).number == min then
          table.insert(getlist, ffuxing_hand[i])
        end
      end
    player.room:obtainCard(player.id, getlist, true, fk.ReasonPrey, player.id, self.name)
    end
  end,
}
xiaotong:addSkill(ffuxing)

Fk:loadTranslationTable{
  [xiaotong.name] = "萧统",
  ["#"..xiaotong.name] = "东宫兰摧",
  ["illustrator:"..xiaotong.name] = "啪啪三国",
  ["designer:"..xiaotong.name] = "中正",

  [llinli.name] = "遴丽",
  [":"..llinli.name] = "至少两张锦囊牌进入弃牌堆时，你可展示手牌，若点数均小于之，你可将之收为手牌。连续发动时，弃置一张上次以此法获得的牌。",
  ["@@"..llinli.name.."-inhand"] = "遴丽",
  ["#"..llinli.name.."-discard"] = "遴丽：请弃置一张因此获得的牌。",
  [llinli.name.."-takeall"] = "获得这些锦囊牌",
  ["#"..llinli.name.."-choice"] = "遴丽：请选择一项",
  [ffuxing.name] = "馥行",
  [":"..ffuxing.name] = "每轮限一次，其他角色的弃牌阶段结束时，你可展示手牌，若与其弃置牌无同名牌，你可获得其中点数最小的牌。",
}

return extension
